<template>
	<view class="preview-container">
		<swiper :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item,index) in previewListModel.previewListPicUrlItems" :key="item._id">
				<image v-if="Math.abs(index - currentIndex)<=1" @click="handleMask" :src="item.picUrl"
					mode="aspectFill"></image>
			</swiper-item>

		</swiper>

		<view class="mask" v-if="isShowMask">
			<view @click="goBack" class="back" :style="{top:getStatusBarHeight()+'px'}">
				<uni-icons type="left" size="30"></uni-icons>

			</view>
			<view class="count">
				{{currentIndex+1}}/{{previewListModel.previewListPicUrlItems.length}}
			</view>
			<view class="time">
				<uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="Date.now()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view @click="openPopup" class="footer-box">
					<uni-icons type="info" size="30"></uni-icons>
					<view class="text">
						信息
					</view>

				</view>



				<view @click="openScorePopup" class="footer-box">
					<uni-icons type="star" size="30"></uni-icons>
					<view class="text">
						{{currentInfo.userScore?currentInfo.userScore:currentInfo.score}}分
					</view>

				</view>
				<view @click="download" class="footer-box">
					<uni-icons type="download" size="30"></uni-icons>
					<view class="text">
						下载
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">

			<view class="info-container">
				<view class="pop-top">
					<view>壁纸信息</view>
					<view class="close-icon" @click="closePopup"><uni-icons type="closeempty" size="20"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y="true">
					<view class="pop-main">
						<view>
							<view class="label">壁纸ID:</view>
							<view class="content">{{previewListModel.previewListPicUrlItems[currentIndex]._id}}</view>
						</view>
						<!-- 		<view>
							<view class="label">分类:</view>
							<view class="content classify">精选图片</view>
						</view> -->
						<view>
							<view class="label">发布者:</view>
							<view class="content">{{currentInfo.nickname}}</view>
						</view>
						<view>
							<view class="label">评分:</view>
							<view class="content" style="display: flex;align-items: center;">
								<uni-rate readonly :touchable="false" v-model="currentInfo.score" />
								<text style="margin-left: 10rpx;font-size: 26rpx;">{{currentInfo.score}}分</text>
							</view>
						</view>
						<view>
							<view class="label">摘要:</view>
							<view class="content">{{currentInfo.description}}</view>
						</view>
						<view>
							<view class="label">标签:</view>
							<view class="content tags">

								<view class="tag" :key="tag" v-for="tag in currentInfo.tabs">{{tag}}</view>

							</view>
						</view>

					</view>
				</scroll-view>

				<view class="statement">
					声明：本图片来源于用户投稿以及互联网，非商业使用，用于免费学习交流。如侵犯了您的利益，可以拷贝壁纸Id举报至平台，邮箱
					3101650137@qq.com，管理将删除侵权壁纸，维护您的权益。
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="scorePopup" background-color="#fff" :is-mask-click="false">
			<view class="scorePopup-container">
				<view class="pop-top">
					<view>{{currentInfo.userScore?'评分过了':' 壁纸信息'}}</view>
					<view class="close-icon" @click="closeScorePopup"><uni-icons type="closeempty"
							size="20"></uni-icons></view>
				</view>
				<view class="main">
					<uni-rate :readonly="currentInfo.userScore" allowHalf v-model="userScore" />
					<text style="color: #ffca3e;margin-left: 15rpx;">{{userScore}}分</text>
				</view>
				<view class="footer">
					<button type="default" plain size="mini" @click="confirmScore"
						:disabled="!userScore || currentInfo.userScore">确认
					</button>
				</view>
			</view>

		</uni-popup>


	</view>

</template>

<script setup lang="ts">
	import { computed, ref } from "vue"
	import { onLoad,onShareAppMessage } from "@dcloudio/uni-app"
	import { getStatusBarHeight } from "../../utils/system"
	import { PreviewListModel } from '../../services/previewModel'
	import { apiDownLoad, apiGetSingleWallPaper, apiUserScore } from "../../api/apis";
	console.log(getStatusBarHeight());
	let isShowMask = ref(true)
	let value = ref(4)
	let userScore = ref<string | number>(0)
	const popup = ref();
	const scorePopup = ref();
	let previewListModel = PreviewListModel.getInstance();
	console.log(previewListModel.previewListPicUrlItems);
	let currentId = ref('')
	let currentIndex = ref(0)
	let currentInfo = computed(() => {
		return previewListModel.previewListPicUrlItems[currentIndex.value]
	})
	onLoad(async (e) => {
		if(e.type=='share'){
			try {
			let res = 	await apiGetSingleWallPaper({id:currentId.value})
			previewListModel.setPreviewList(res);
			} catch (error) {
				//TODO handle the exception
				console.log(error);
			}
			
		}
		currentId.value = e.id
		currentIndex.value = previewListModel.previewListPicUrlItems.findIndex(item => item._id == e.id);
	})
	function goBack() {
		uni.navigateBack({
			fail: () => {
				uni.reLaunch({
					url:"/pages/index/index"
				})
			}
		})
	}
	function handleMask() {
		isShowMask.value = !isShowMask.value
	}
	function openPopup() {
		popup.value.open();
	}
	function closePopup() {
		popup.value.close();
	}
	function openScorePopup() {
		userScore.value = previewListModel.previewListPicUrlItems[currentIndex.value].userScore ? previewListModel.previewListPicUrlItems[currentIndex.value].userScore : 0;
		scorePopup.value.open();
	}
	function closeScorePopup() {
		scorePopup.value.close();
	}
	async function confirmScore() {
		let { _id: wallId, classid } = currentInfo.value
		try {
			let res = await apiUserScore({ wallId, classid, userScore: userScore.value })
			previewListModel.setPreviewAttr(currentIndex.value, 'userScore', userScore.value)



		} catch (error) {
			//TODO handle the exception
		}
		finally {
			userScore.value = 0;
			scorePopup.value.close();
		}


	}

	function swiperChange(e) {
		console.log(e);
		currentIndex.value = e.detail.current;
	}

	async function download() {
		// #ifdef H5

		uni.showModal({
			title: '下载',
			showCancel: false,
			content: '请长按保存壁纸'
		})
		// #endif

		// #ifndef H5
		try {
			let { classid, _id: wallid } = currentInfo.value
			let res = await apiDownLoad({ classid, wallid });
			if (res.errCode != 0) throw res.errcode;

			uni.getImageInfo({
				src: currentInfo.value.picUrl,
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: () => {
							uni.showToast({
								title: '已保存，请进入相册查看'
							})
						},
						fail: (err) => {

							if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
								return
							} else {
								uni.showModal({
									title: '提示',
									content: '需要获取相册权限',
									success: ({ confirm }) => {
										if (confirm) {
											uni.openSetting({
												success: (setting) => {
													if (setting.authSetting['scope.writePhotosAlbum']) {
														uni.showToast({
															title: '获取授权成功'
														})
													} else {
														uni.showToast({
															title: '获取授权失败'
														})
													}
												}
											})
										}

									}
								})

							}

						}
					})
				}
			})
		} catch (error) {
			//TODO handle the exception
			console.log(error);
		}



		// #endif
	}
	
	onShareAppMessage(e=>{
		return{
			title:currentInfo.value.nickname,
			path:'pages/preview/preview?id='+currentId.value+'&type=share'
		}
	})
</script>

<style lang="scss" scoped>
	.preview-container {
		position: relative;
		width: 100%;
		height: 100vh;

		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;

			}
		}

		.pop-top {
			position: relative;
			text-align: center;
			font-size: 26rpx;
			color: $text-font-color-sub;

			.close-icon {
				padding: 0 10rpx;
				position: absolute;
				right: 0;
				top: 0;
			}
		}

		.mask {
			.back {
				position: absolute;
				left: 10px;
				top: 40px;
				border: 1px solid #777;
				border-radius: 50%;
				backdrop-filter: blur(10px);
			}

			.count,
			.time,
			.date,
			{
			position: absolute;
			left: 50%;

			transform: translate(-50%, 0);
			color: #fff;
		}

		.count {
			top: 10vh;
			padding: 8rpx 28rpx;
			backdrop-filter: blur(10px);
			background-color: rgba(0, 0, 0, .3);
			font-size: 28rpx;
			border-radius: 40rpx;
		}

		.time {
			font-size: 140rpx;
			top: calc(10vh + 60rpx);
			font-weight: 100;
			text-shadow: 0 4rpx rbga(0, 0, 0, .3);
		}

		.date {
			top: calc(10vh + 240rpx);
			text-shadow: 0 4rpx rbga(0, 0, 0, .3);
			font-size: 34rpx;
		}

		.footer {
			position: absolute;
			left: 50%;
			transform: translate(-50%, 0);
			bottom: 230rpx;
			padding: 30rpx;
			width: 65vw;
			height: 120rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			gap: 60rpx;
			background-color: rgba(255, 255, 255, .8);
			border-radius: 60rpx;
			box-shadow: 0 2rpx 0 rgba(0, 0, 0, .1);

			.footer-box {
				display: flex;
				flex-direction: column;
				align-items: center;

				.text {
					font-size: 26rpx;
					color: $text-font-color-sub;
				}
			}
		}

	}

	.info-container {
		padding: 30rpx;
		background-color: #fff;
		border-top-right-radius: 30rpx;
		border-top-left-radius: 30rpx;

		scroll-view {
			max-height: 60vh;
		}

		.pop-main {
			>view {
				margin: 16rpx 0;
				display: flex;
				flex-wrap: nowrap;
				line-height: 1.7em;
				font-size: 30rpx;

				.label {
					width: 100rpx;
					color: $text-font-color-sub;

				}

				.content {
					flex: 1
				}

				.classify {
					color: $brand-theme-color;
				}

				.tags {
					display: flex;
					gap: 15rpx;

					.tag {
						padding: 0rpx 25rpx;
						border: 1px solid $brand-theme-color;
						color: $brand-theme-color ;
						border-radius: 40rpx;
						font-size: 22rpx;
						margin: 0 10rpx;
					}
				}
			}
		}

		.statement {
			margin: 20rpx 0;
			padding: 20rpx;
			background-color: #f6f6f6;
			border-radius: 15rpx;
			color: #666;
			line-height: 1.6em;
		}
	}

	.scorePopup-container {
		padding: 20rpx;
		width: 60vw;
		border-radius: 30rpx;

		.main {
			padding: 30rpx 0;
			display: flex;
			justify-content: center;
		}

		.footer {
			padding: 10rpx 0;
			display: flex;
			justify-content: center;
		}

	}
	}
</style>